﻿using System.Linq;
using Contracts.Entities;
using Contracts.Library;
using Model.MovieElements;
using System.Collections.Generic;
using Model.Movie;

namespace Model.WebImport
{
    public class WriteTmdbMovie
    {
        private MovieDatabaseEntities entities;
        private WriteBackdrops writeBackdrops;

        public WriteTmdbMovie()
        {
            this.entities = new MovieDatabaseEntities();
            this.writeBackdrops = new WriteBackdrops(entities);
        }

        public void Update(TmdbMovie tmdbMovie, int movieId, byte[] cover, IEnumerable<byte[]> backdrops)
        {
            var movie = entities.Movies.SingleOrDefault(m => m.Id == movieId);        

            movie.OriginalName = tmdbMovie.Original_name;
            movie.Overview = tmdbMovie.Overview;
            movie.TmdbRating = (short)tmdbMovie.Rating;

            if (tmdbMovie.Released != null)
                movie.ReleaseYear = (short)tmdbMovie.Released.Year;
               
            movie.RuntimeMin = (short)tmdbMovie.Runtime;
            movie.Revenue = tmdbMovie.Revenue.ToString();
            movie.Budget = tmdbMovie.Budget.ToString();
            movie.TrailerUrl = tmdbMovie.Trailer;
            movie.Cover = cover;

            entities.SaveChanges();

            writeBackdrops.Insert(movie, backdrops);

            var actorItems = ActorConverter.GetElements(tmdbMovie.Cast.Where(m => m.Job == "Actor"));
            var actorWriter = new WriteActors(entities, movie);
            actorWriter.Process(actorItems);

            var directorItems = DirectorConverter.GetElements(tmdbMovie.Cast.Where(m => m.Job == "Director"));
            var directorWriter = new WriteDirectors(entities, movie);
            directorWriter.Process(directorItems);

            var genreItems = GenreConverter.GetElements(tmdbMovie.Categories.Where(m => m.Type == "genre"));
            var genreWriter = new WriteGenres(entities, movie);
            genreWriter.Process(genreItems);

            var countryItems = CountryConverter.GetElements(tmdbMovie.Countries);
            var countryWriter = new WriteCountries(entities, movie);
            countryWriter.Process(countryItems);

            var studioItems = StudioConverter.GetElements(tmdbMovie.Studios);
            var studioWriter = new WriteStudios(entities, movie);
            studioWriter.Process(studioItems);
        }
    }
}
